package com.xb.service.imp;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.*;
import com.xb.mapper.*;
import com.xb.service.IUserService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Service业务层处理
 */
@Service
public class UserServiceImp implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private ScheduledTaskMapper taskMapper;
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private OutpatientQueueMapper queueMapper;

    Digester digester = new Digester(DigestAlgorithm.MD5);

    String salt;
    /**
     * 查询
     * @param id ID
     * @return
     */


    /**
     * 分页查询列表
     *
     * @param user
     * @return
     */
    @Override
    public Result selectUserList(User user, Integer page, Integer limit) {
        Result result = new Result();
        PageHelper.startPage(page, limit);
        List<User> list = userMapper.searchAllUserList(user);
        PageInfo<User> userPageInfo = new PageInfo<>(list);
        if (userPageInfo.getList() != null) {
            result.setMessage("查询成功");
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setTotal(userPageInfo.getTotal());
            result.setData(userPageInfo.getList());
        }
        return result;
    }

    @Override
    public User selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 查询
     *
     * @param username 账号
     * @return 对象
     */
    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }


    @Override
    public Result resetPassword(Integer id) {
        Result result = new Result();
        salt = digester.digestHex(String.valueOf(System.currentTimeMillis()));
        digester.setSalt(salt.getBytes());
        User user = new User();
        user.setSalt(salt);
        user.setPassword(digester.digestHex("123"));
        user.setId(id);
        user.setPwdUpdateDate(new Date());
        if (userMapper.resetPassword(user) > 0) {
            result.setMessage("重置成功！新密码为：123");
            result.setStatus(Result.RESPONSE_SUCCESS);
        } else {
            result.setMessage("重置失败！");
        }
        return result;
    }

    /**
     * 查询列表
     *
     * @param user
     * @return
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增
     *
     * @param user
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertUser(User user, List<Integer> roleIds) {
        try {
            salt = digester.digestHex(UUID.randomUUID().toString().toLowerCase().replace("-", "") + System.currentTimeMillis());
            digester.setSalt(salt.getBytes());
            user.setPlainPassword(user.getPassword());
            user.setPassword(digester.digestHex(user.getPassword()).toUpperCase());
            user.setSalt(salt);
            user.setSex("男");
            user.setCreateDatetime(new Date());
            if (userMapper.insertUser(user) == 0) {
                throw new IllegalAccessException("插入数据失败");
            }
            UserRole userRole;
            for (Integer roleId : roleIds) {
                userRole = new UserRole();
                Role role = roleMapper.selectRoleById(roleId);
                userRole.setUid(user.getId());
                userRole.setRoleId(roleId);
                userRole.setDescription(user.getEmail() + "——" + role.getRole());
                userRole.setCreateDatetime(new Date());
                if (userRoleMapper.insertUserRole(userRole) == 0) {
                    throw new IllegalAccessException("插入数据失败");
                }
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return false;
        }

    }

    @Transactional
    @Override
    public Result checkDbStatus() {
        Result result = new Result();
        try {
            List<Register> registers = taskMapper.checkRegisterEffective();
            List<OutpatientQueue> outpatientQueues = taskMapper.checkOutpatientQueueEffective();
            List<User> users = userMapper.selectAllUser();
            if (registers != null) {
                for (Register register : registers) {
                    Date appointmentDate = register.getCreateDatetime(); // 替换为你的预约日期
                    // 获取今天的日期
                    LocalDate today = LocalDate.now();
                    // 将预约日期转换为LocalDate类型
                    LocalDate appointmentLocalDate = appointmentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 判断预约日期是否在今天
                    if (!appointmentLocalDate.equals(today)) {
                        register.setRegisterStatus(-1);
                        if (registerMapper.updateRegister(register) == 0) {
                            throw new RuntimeException("register修改状态失败！");
                        }
                    }
                }
            }
            if (outpatientQueues != null) {
                for (OutpatientQueue outpatientQueue : outpatientQueues) {
                    Date appointmentDate = outpatientQueue.getCreateDatetime(); // 替换为你的预约日期
                    // 获取今天的日期
                    LocalDate today = LocalDate.now();
                    // 将预约日期转换为LocalDate类型
                    LocalDate appointmentLocalDate = appointmentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 判断预约日期是否在今天
                    if (!appointmentLocalDate.equals(today)) {
                        outpatientQueue.setStatus(0);
                        if (queueMapper.updateOutpatientQueue(outpatientQueue) == 0) {
                            throw new RuntimeException("outpatient修改状态失败！");
                        }
                    }
                }
            }
            if (users != null) {
                for (User user : users) {
                    user.setNowNum(registerMapper.selectNowNum(user));
                    if (userMapper.updateUser(user) == 0) {
                        throw new RuntimeException("user修改状态失败！");
                    }
                }
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("出现了异常，请停止挂号等操作并联系管理员！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
    }


    /**
     * 修改
     *
     * @param user
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public Result updateUserInfo(User user, HttpSession session) {
        Result result = new Result();
        String email = (String) session.getAttribute("email");
        user.setEmail(email);
        if (userMapper.updateUser(user) > 0) {
            result.setStatus(Result.RESPONSE_SUCCESS);
        } else {
            result.setMessage("修改失败！");
        }
        return result;
    }

    @Override
    public Result changePassword(ChangePasswordReqVO reqVO, HttpSession session) {
        Result result = new Result();
        try {
            if (!reqVO.getNewPassword().equals(reqVO.getOkPassword())) {
                result.setMessage("两次密码不相同");
                return result;
            }
            String email = (String) session.getAttribute("email");
            User user = userMapper.selectUserByEmail(email);
            digester.setSalt(user.getSalt().getBytes());
            reqVO.setPassword(digester.digestHex(reqVO.getPassword()).toUpperCase());
            if (reqVO.getPassword().equals(user.getPassword())) {
                salt = digester.digestHex(String.valueOf(System.currentTimeMillis()));
                digester.setSalt(salt.getBytes());
                user.setSalt(salt);
                user.setPassword(digester.digestHex(reqVO.getNewPassword()).toUpperCase());
                user.setPwdUpdateDate(new Date());
                if (userMapper.updateUser(user) > 0) {
                    result.setStatus(Result.RESPONSE_SUCCESS);
                    result.setMessage("修改成功！");
                } else {
                    result.setMessage("修改失败");
                }
            } else {
                result.setMessage("你的原始密码不正确！");
            }
            return result;
        } catch (Exception e) {
            result.setMessage("请联系管理员");
            return result;
        }
    }

    @Transactional
    @Override
    public Result insert(User user) {
        Result result = new Result();
        try {
            if (userMapper.selectUserByEmail(user.getEmail()) != null) {
                throw new IllegalAccessException("此邮箱已被人注册！");
            }
            salt = digester.digestHex(UUID.randomUUID().toString().toLowerCase().replace("-", "") + System.currentTimeMillis());
            digester.setSalt(salt.getBytes());
            user.setPlainPassword(user.getPassword());
            user.setPassword(digester.digestHex(user.getPassword()).toUpperCase());
            user.setSalt(salt);
            if (userMapper.insertUser(user) == 0) {
                throw new IllegalAccessException("注册失败！");
            }
            if (!user.getRoleIds().isEmpty()) {
                user.setDescription("admin-add-user");
                if (userRoleMapper.insertUserRoleByUser(user) == 0) {
                    throw new IllegalAccessException("注册失败！");
                }
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("添加成功！");
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage("请联系管理员！");
            return result;
        }
    }

    @Transactional
    @Override
    public Result update(User user) {
        Result result = new Result();
        try {
            if (!userMapper.selectUserById(user.getId()).getEmail().equals(user.getEmail())) {
                if (userMapper.selectUserByEmail(user.getEmail()) != null) {
                    throw new IllegalAccessException("此邮箱已存在");
                }
            }
            if (userMapper.updateUserById(user) == 0) {
                throw new IllegalAccessException("user修改失败！");
            }
            if (!userRoleMapper.selectUserRoleByUid(user.getId()).isEmpty()) {
                if (userRoleMapper.deleteUserRoleByUid(user.getId()) == 0) {
                    throw new IllegalAccessException("userRole删除失败！");
                }
            }
            user.setDescription("admin-edit-user-role");
            if (!user.getRoleIds().isEmpty()) {
                if (userRoleMapper.insertUserRoleByUser(user) == 0) {
                    throw new IllegalAccessException("userRole增加失败！");
                }
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("修改成功");
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage("ERROR！请联系管理员");
            return result;
        }
    }

    @Transactional
    @Override
    public Result del(Integer id) {
        Result result = new Result();
        try {
            if (!queueMapper.searchPendingPatientsByUserId(id).isEmpty()) {
                throw new IllegalAccessException("此用户还有待诊患者！");
            }
            if (userMapper.deleteUserByUid(id) == 0) {
                throw new IllegalAccessException("用户删除失败！");
            }
            if (userRoleMapper.deleteUserRoleByUid(id) == 0) {
                throw new IllegalAccessException("用户删除失败！");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("删除成功！此操作不可逆！");
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage("ERROR！请联系管理员");
            return result;
        }
    }
}
